/**
 * 
 */
package com.ez.supervise.action.base;

import java.io.IOException;
import java.io.PrintWriter;

import com.ez.supervise.model.dto.LoginUser;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * @author searph.wang
 * @email searph.wang@gmail.com
 * @Created at 2009-7-24
 */
public class BaseJsonAction extends BaseAction {

    private static final long serialVersionUID = -193209190224759385L;
    public String jsonString;
    protected boolean success;
    public static final String RESULT_SUCCESS = "{success:true}";
    public static final String RESULT_FAIL = "{success:false}";
    public static final String RESULT_LONGIN_FAIL = "{success:false, logout: true}";
    public static final String JS_CONTENT_TYPE = "text/javascript;charset=UTF-8";
    public static final String JSON_CONTENT_TYPE = "application/json;charset=UTF-8";

    public void outJsonString(String str) {
	getResponse().setContentType(JS_CONTENT_TYPE);
	outString(str);
    }

    public void outJson(Object obj) {
	outJsonString(JSONObject.fromObject(obj).toString());
    }

    public void outJsonArray(Object array) {
	outJsonString(JSONArray.fromObject(array).toString());
    }

    public void outString(String str) {
	try {
	    getResponse().getWriter().write(str);
	    getResponse().getWriter().flush();
	} catch (IOException e) {
	    e.printStackTrace();
	} finally {
	    try {
		getResponse().getWriter().close();
	    } catch (IOException e) {
		e.printStackTrace();
	    }
	}

    }

    public void outXMLString(String xmlStr) {
	getResponse().setContentType("application/xml;charset=UTF-8");
	outString(xmlStr);
    }

    public boolean isSuccess() {
	return success;
    }

    public void setSuccess(boolean success) {
	this.success = success;
    }

    public boolean checkLogin() {
	if(loginUser == null) {
	    outJsonString(RESULT_LONGIN_FAIL);
	    return false;
	}
	return true;
    }
}
